<template>
  <div class="login">
    <div class="contain">
        <div class="top">
            <h3>登录</h3>
            <p>还没有账户? <router-link to="/register" class="toRegister">点击注册</router-link></p>
        </div>
        <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
            <el-form-item
             label="账号"
             prop="phone"
             :rules="[
                { required: true, message: '手机号不能为空', trigger: 'blur' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
            ]"  >
                <el-input v-model.number="formLabelAlign.phone" maxlength="11"></el-input>
            </el-form-item>
            <el-form-item
            label="密码"
            prop="pass"
             :rules="[
            { required: true, message: '密码不能为空'},
            ]"
            >
                <el-input type="password" v-model="formLabelAlign.pass" show-password maxlength="20"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="submitButton" @click="submit">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/login'
export default {
  name: 'loginRight',
  data () {
    return {
      formLabelAlign: {
        phone: '',
        pass: ''
      },
      labelPosition: 'right'
    }
  },
  methods: {
    async submit () {
      if (!/^1[3-9]\d{9}$/.test(this.formLabelAlign.phone)) {
        this.$message({
          showClose: true,
          message: '请输入正确的手机号码',
          type: 'error'
        })
        return
      }
      if (!this.formLabelAlign.pass || this.formLabelAlign.pass === '') {
        this.$message({
          showClose: true,
          message: '请输入密码',
          type: 'error'
        })
        return
      }
      const res = await login(this.formLabelAlign.phone, this.formLabelAlign.pass)
      if (res.code === -5) {
        this.$message({
          showClose: true,
          message: '用户已在别处登录',
          type: 'error'
        })
        return
      }
      if (res === null || res.data.userId === null) {
        this.$message({
          showClose: true,
          message: '账户不存在或密码错误',
          type: 'error'
        })
        return
      }
      this.$message({
        showClose: true,
        message: '登录成功',
        type: 'success'
      })
      this.$store.commit('user/setUserInfo', { token: res.data.token, userId: res.data.user.userId })
      this.$router.replace('/layout')
    }
  }
}
</script>

<style scoped>
.login {
    width: 80%;
}
.contain {
    width: 100%;
}
.top {
    display: flex;
    justify-content: space-between;
}
.contain h3 {
    margin-left: 80px;
    margin-bottom: 20px;
    font-size: 25px;
}
.submitButton {
    width: 100%;
}
</style>
